import 'package:json_annotation/json_annotation.dart';
import 'package:multi_shop/models/address.dart';
import 'package:multi_shop/models/order_item.dart';
import 'package:multi_shop/pages/order_list.dart';

part 'order.g.dart';

@JsonSerializable(explicitToJson: true)
class MallOrder {
  @JsonKey(fromJson: _toInt, defaultValue: 0)
  final int id; // 订单ID

  @JsonKey(fromJson: _toInt, defaultValue: 0)
  final int userId; // 用户ID

  @JsonKey(defaultValue: '')
  final String orderNo; // 订单编号

  @JsonKey(fromJson: _toDouble, defaultValue: 0.0)
  final double totalAmount; // 订单总金额

  @JsonKey(fromJson: _statusFromJson, toJson: _statusToJson)
  final OrderStatus status;

  @JsonKey(fromJson: _toInt, defaultValue: 0)
  final int addressId; // 地址id

  @JsonKey(fromJson: _toInt, defaultValue: 0)
  final int payMethod; // 支付方式

  @JsonKey(defaultValue: [], fromJson: _toItems)
  final List<OrderItem> items; // 订单商品

  final String createdAt; // 订单创建时间
  final Address? address; // 地址

  MallOrder({
    required this.id,
    required this.userId,
    required this.orderNo,
    required this.totalAmount,
    required this.status,
    required this.addressId,
    required this.payMethod,
    required this.items,
    required this.createdAt,
    this.address,
  });
  factory MallOrder.fromJson(Map<String, dynamic> json) =>
      _$MallOrderFromJson(json);

  Map<String, dynamic> toJson() => _$MallOrderToJson(this);

  // ----------------- 辅助函数 -----------------
  /// 自定义转换方法
  static OrderStatus _statusFromJson(int code) => OrderStatus.fromCode(code);

  static int _statusToJson(OrderStatus status) => status.code;

  static int _toInt(Object? v) {
    if (v == null) return 0;
    if (v is int) return v;
    if (v is double) return v.toInt();
    if (v is String && v.trim().isNotEmpty) {
      return int.tryParse(v) ?? double.tryParse(v)?.toInt() ?? 0;
    }
    return 0;
  }

  static double _toDouble(Object? v) {
    if (v == null) return 0.0;
    if (v is double) return v;
    if (v is int) return v.toDouble();
    if (v is String && v.trim().isNotEmpty) {
      return double.tryParse(v) ?? 0.0;
    }
    return 0.0;
  }

  static List<OrderItem> _toItems(Object? v) {
    if (v == null) return [];
    if (v is List) {
      return v
          .map((e) => OrderItem.fromJson(Map<String, dynamic>.from(e)))
          .toList();
    }
    return [];
  }
}
